// pages/account/account-detail.js
import * as echarts from '../../../components/ec-canvas/echarts';
const app = getApp()

const {  wxPost, wxGet, commonShare, serviceBusy } = require('../../../utils/common.js')
var pieCharPlan = null
var pieCharActual = null
var historyChart = null


Page({
  data: {
    guideShow: true,
    homeShow: false,
    ecPlan: {
      onInit: function(canvas, width, height, dpr) {
        pieCharPlan = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(pieCharPlan)
        return pieCharPlan
      }
    },
    ecActual: {
      onInit: function(canvas, width, height, dpr) {
        pieCharActual = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(pieCharActual)
        return pieCharActual
      }
    },
    history: {
      onInit: function(canvas, width, height, dpr) {
        historyChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(historyChart)
        return historyChart
      }
    },
    waitLoading: true,
  },
  tabSelect: function() {
    if (!this.data.guideShow) {
      this.setData({
        guideShow: true,
        homeShow: false
      })
    } else {
      this.setData({
        guideShow: false,
        homeShow: true
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var pages = getCurrentPages()
    var prevPage = pages[pages.length - 2] //上一个页面
    if (prevPage) {
      console.info(prevPage.data)
      this.setData({
        currency: prevPage.data.info.settlementCurrency ||'',
        infoId: options.infoId || '' 
      })
    }else{
      this.setData({ 
        infoId: options.infoId || '' 
      })
    }
    
    setTimeout(() => {
      this.loadProfileInfo()
    }, 100)

  },
  loadProfileInfo() {
    wx.showLoading({
      title: '加载中...'
    })
    wxGet('/assetsInfo/profileInfo', { infoId: this.data.infoId }, ({  data }) => {
      if (data && data['errorCode'] === 0) {
        const {  serviceInfo,   summary } = data
        let list1 = [],  list2 = [], list3 = []
        if (summary && summary.assetsCombo) {
          const {   assetsCombo } = summary
          assetsCombo && assetsCombo.forEach(o => {
            let {  assetType ,fundType } = o.fundId
            if ((fundType === '净值型' && o['portion'] !== 0) || (fundType === '非净值型' && o['marketValueExchange'] !== '0.00')) {
                if (assetType === '权益类') {
                  list1.push(o)
                } else if (assetType === '债类+衍生品类') {
                  list2.push(o)
                } else if (assetType === '现金类') {
                  list3.push(o)
                }
                o.portion = o.portion ? o.portion.toFixed(2) : o.portion
            }
          })
        }
        if(serviceInfo && serviceInfo.structure){
          serviceInfo.structureStr=serviceInfo.structure.replace(':','%:')+'%'
        }else if(serviceInfo){
           serviceInfo.structureStr=''
        }
        this.setData({ serviceInfo, summary, list1, list2, list3 })
        const actualData=[]
        let { equityREITsAssetsTypeMkvRatio, debtAssetsTypeMkvRatio, cashAssetsTypeMkvRatio } = summary||{}
        if (equityREITsAssetsTypeMkvRatio){
          equityREITsAssetsTypeMkvRatio = equityREITsAssetsTypeMkvRatio.replace('%', '')
          if (equityREITsAssetsTypeMkvRatio!='0.00'){
            actualData.push({
              value: equityREITsAssetsTypeMkvRatio,
              name: '权益类'+equityREITsAssetsTypeMkvRatio+'%'
            })
          }
        }
        if (debtAssetsTypeMkvRatio) {
          debtAssetsTypeMkvRatio = debtAssetsTypeMkvRatio.replace('%','')
          if (debtAssetsTypeMkvRatio != '0.00') {
            actualData.push({
              value: debtAssetsTypeMkvRatio,
              name: '债类+衍'+debtAssetsTypeMkvRatio+'%'
            })
          }
        }
        if (cashAssetsTypeMkvRatio) {
          cashAssetsTypeMkvRatio = cashAssetsTypeMkvRatio.replace('%', '')
          if (cashAssetsTypeMkvRatio != '0.00') {
            actualData.push({
              value: cashAssetsTypeMkvRatio,
              name: '现金类'+cashAssetsTypeMkvRatio+'%'
            })
          }
        }
        var option = {
          backgroundColor: "#ffffff",
          color: ["#e8968f", "#274189", '#f8ca4b'],
          series: [{
            label: {
              normal: {
                fontSize: 14
              }
            },
            type: 'pie',
            center: ['50%', '50%'],
            radius: ['40%', '60%'],
            data: actualData
          }]
        };
        pieCharActual.setOption(option)
        //新竹规划
        const { structure } = serviceInfo || {}
        if(structure){
          const { 0: eq, 1: debt } = structure.split(':')
          var option = {
            backgroundColor: "#ffffff",
            color: ["#e8968f", "#274189", '#f8ca4b'],
            series: [{
              label: {
                normal: {
                  fontSize: 14
                }
              },
              type: 'pie',
              center: ['50%', '50%'],
              radius: ['40%', '60%'],
              data: [{ value: eq, name: '权益类'+eq+'%' }, { value: debt, name: '债类+衍'+debt+'%' }]
            }]
          };
          pieCharPlan.setOption(option)
        }
       this.drawPie(data.history)
      } else if (data && data['errorCode'] === 100) {
        serviceBusy()
      }
    }, null, () => {
      wx.hideLoading()
      this.setData({
        waitLoading: false
      })
    })
  },
  drawPie :function( history) {
    const that=this
    historyChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {            // 坐标轴指示器，坐标轴触发有效
          type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
        }
      },
      color: ['#f8ca4b','#274189', '#e8968f'],
      legend: {
        data: ['现金类','债类+衍生品类', '权益类'],
        textStyle: {
          //fontSize: 26
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: history.map(o=> o.date)
      },
      yAxis: {
        type: 'value',
        axisLabel:{
          formatter:function(val){
            return val+'%'
          }  
        } 
      },
      series: that.maskSeriesData(history),
      label: {
        normal: {
          show: true,
          textStyle: {
           // fontSize: 26
          }
        },
        emphasis: {
          show: true
        }
      }
    })
  },
  maskSeriesData (history) {
    const itemWidth=40
    return [{
      name: '现金类',
      type: 'bar',
      stack: '总量',
      barWidth: itemWidth,//柱图宽度
      label: {
        show: true,
        position: 'insideRight'
      },
      textStyle: {
       // fontSize: 26
      },
      data: history.map(o=> this.formatNum((o.cash||'').replace('%','')))
    },
      {
        name: '债类+衍生品类',
        type: 'bar',
        stack: '总量',
        barWidth: itemWidth,//柱图宽度
        label: {
          show: true,
          position: 'insideRight',
          textStyle: {
            //fontSize: 15
          }
        },
        data: history.map(o=> this.formatNum((o.debt||'').replace('%','')))
      }, {
        name: '权益类',
        type: 'bar',
        stack: '总量',
        barWidth: itemWidth,//柱图宽度
        label: {
          show: true,
          position: 'insideRight',
          textStyle: {
            //fontSize: 15
          }
        },
        data: history.map(o=> this.formatNum((o.equity||'').replace('%','')))
      }]
  },
  formatNum(num){
    if(parseFloat(num)>1){
      return num
    }
    return null
  },
  onShareAppMessage: function() {
    return commonShare()
  }
})